﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace VCDepend.Engine
{
  public static class SolutionReader
  {
    public static Solution CreateFromFilename(string filename)
    {
      using (Stream stream = File.OpenRead(filename))
      {
        string basePath = Path.GetDirectoryName(filename);
        return CreateFromStream(basePath, stream);
      }
    }

    public static Solution CreateFromStream(string basePath, Stream contentStream)
    {
      string contents = ReadStream(contentStream);
      return Create(basePath, contents);
    }

    public static Solution Create(string basePath, string contents)
    {
      string version = ExtractSolutionVersion(contents);
      switch (version)
      {
        case "8.00":
          return new Solution71(basePath, contents);

        case "9.00":
          return new Solution80(basePath, contents);

        case "10.00":
          return new Solution90(basePath, contents);

        default:
          throw new UnknownSolutionFormatException("Parser did not recognize solution file format. Version was '" + version + "'.");
      }
    }

    private static string ReadStream(Stream stream)
    {
      StreamReader reader = new StreamReader(stream);
      return reader.ReadToEnd();
    }

    private static string ExtractSolutionVersion(string contents)
    {
      const string pattern = "Microsoft Visual Studio Solution File, Format Version (?<version>[0-9.]*)";
      
      Match match = Regex.Match(contents, pattern, RegexOptions.Multiline);
      if (match == null)
        return string.Empty;

      return match.Groups["version"].Value;
    }
  }
}
